import { cartItem, IApiRes } from "@/types/data";
import request from "@/utils/request";
import { isTemplateNode } from "@vue/compiler-core";
import { defineStore } from "pinia";
import useStore from "..";
import user from "./user";

const useCartStore = defineStore('cart', {
    // 状态
    state() {
        return {
            list: [] as cartItem[] // 购物车数组
        }
    },
    // 计算
    getters: {
        effectiveList(): cartItem[] {
            return this.list.filter(it=>it.isEffective)
        },
        effectiveListCounts(): number {
            return this.effectiveList.reduce((sum, item) => sum + item.count, 0)
        },
        effectiveListPrice(): string {
            return this.effectiveList.reduce((sum, item) => sum + item.count * Number(item.price), 0).toFixed(2)
        },
        selectedAll(): boolean{
            return this.effectiveList.every(item=>item.selected)
        },
        selectedList(): cartItem[]{
            return this.effectiveList.filter(it=>it.selected)
        },
        selectedCount(): number{
            return this.selectedList.reduce((acc, cur) => {
                return acc + cur.count
            },0)
        },
        selectedPrice(): number {
            return this.selectedList.reduce((acc, cur) => {
                return acc + cur.count * +cur.price
            }, 0)
        },
        isLogin():boolean {
            const userInfo = user()
            return Boolean(userInfo.profile.token)
        }
    },
    // 方法
    actions: {
        async addCart(data: cartItem) {
            if (this.isLogin) {
                await request.post('/member/cart', data)
                this.getCartList()
            } else {
                console.log(111);
                const d = this.list.find(it => it.skuId === data.skuId)
                if (d) {
                    d.count += data.count
                } else {
                    this.list.push(data)
                }
           }
        },
        // 获取购物车列表
        async getCartList() {
            if (this.isLogin) {
                const res = await request.get<IApiRes<cartItem[]>>('/member/cart')
                this.list = res.data.result
            } else {
                console.log('没有登录，从本地取数据')
                // 遍历发送请求, 校验更新sku商品的库存和价格, 是否有效
                this.list.forEach(async (cartItem) => {
                    const { skuId } = cartItem
                    // 根据 skuId 获取最新商品信息
                    const res = await request.get<IApiRes<cartItem>>(
                        `/goods/stock/${skuId}`
                    )
                    // 保存最新商品信息
                    const lastCartInfo = res.data.result
                    // 更新商品现价
                    cartItem.nowPrice = lastCartInfo.nowPrice
                    // 更新商品库存
                    cartItem.stock = lastCartInfo.stock
                    // 更新商品是否有效
                    cartItem.isEffective = lastCartInfo.isEffective
                })
            }
        },
        //删除商品
        async delCart(skuId:string[]) {
            if (this.isLogin) {
                await request.delete('/member/cart', {
                    data: { ids: skuId }
                })
                this.getCartList()
            } else {
                this.list.filter(it => {
                    return skuId.includes(it.skuId)
                })
            }
        },
        // 修改购物车商品
        async updateCart(
            skuId: string,
            data: { selected?: boolean; count?: number }
        ) {
            if (this.isLogin) {
                await request.put(`/member/cart/${skuId}`, data)
                // 重新获取最新购物车列表
                this.getCartList()
            } else {
                const g = this.effectiveList.find(it => it.skuId === skuId)
                if (!g) return
                if (data.selected !== undefined) {
                    g.selected=data.selected
                }
                if (data.count !== undefined) {
                    g.count = data.count
                }
            }
        },
        async updateCartAllSelected(isSelected: boolean) {
            if (this.isLogin) {
                await request.put('/member/cart/selected', {
                    selected: isSelected,
                })
                // 获取购物车列表
                this.getCartList()
            } else {
                this.list.forEach((item) => {
                    item.selected = isSelected
                })
          }
        },
        clearCart() {
            this.list = []
        }
    },
    
});

export default useCartStore;